package com.quanyue.music.system.controller;

import com.quanyue.auto.cache.CacheService;
import com.quanyue.auto.fs.FsProperties;
import com.quanyue.auto.fs.StoreService;
import com.quanyue.auto.util.KeyGenerator;
import com.quanyue.auto.util.ServiceResult;
import com.quanyue.auto.web.Principal;
import com.quanyue.music.domain.constant.CacheConstants;
import com.quanyue.music.system.service.SplitMp3Service;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tika.mime.MimeType;
import org.apache.tika.mime.MimeTypeException;
import org.apache.tika.mime.MimeTypes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Api(tags = "文件接口")
@RestController
public class FileController {

    @Autowired
    private StoreService storeService;
    @Autowired
    private SplitMp3Service splitMp3Service;
    @Autowired
    private CacheService cacheService;

    @ApiOperation(value = "上传图片", produces = MediaType.MULTIPART_FORM_DATA_VALUE)
    @PostMapping(value = "/api/image/file/upload")
    public ServiceResult <String> upload(@RequestParam("file") MultipartFile file, @ApiIgnore Principal manager) throws IOException, MimeTypeException {
        MimeType type = MimeTypes.getDefaultMimeTypes().forName(file.getContentType());
        return ServiceResult.success(storeService.saveFile(manager.getMerchantNo(), file.getBytes(), type.getExtension()));
    }

    @ApiOperation(value = "腾讯云上传MP3", produces = MediaType.MULTIPART_FORM_DATA_VALUE)
    @PostMapping(value = "/api/music/file/upload")
    public ServiceResult <String> uploadMusic(@RequestParam("file") MultipartFile file, @ApiIgnore Principal manager) throws MimeTypeException {
        List <String> urls = new ArrayList <>(4);
//        List<MultipartFile> multipartFiles = splitMp3Service.split(file);
//        String uuid = KeyGenerator.uuid();
//        for (int i = 0; i < multipartFiles.size(); i++) {
//            try {
//                urls.add(storeService.saveFile(manager.getMerchantNo(), multipartFiles.get(i).getBytes(), ".mp3", uuid + i));
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        }
//        if (urls.isEmpty()) return ServiceResult.success("fail");
//        return ServiceResult.success(urls.get(0));
        return null;
    }

    @ApiOperation(value = "nginx上传MP3", produces = MediaType.MULTIPART_FORM_DATA_VALUE)
    @PostMapping(value = "/api/music/file/upload/remote")
    public ServiceResult <String> uploadMusicToRemote(@RequestParam("file") MultipartFile file, @ApiIgnore Principal manager) throws IOException, MimeTypeException {
//        try {
//            if (file.getBytes().length < 10 * 1024 * 1024) {
//                // 转换MultipartFile为File
//                File directory = new File(path);
//                if (!directory.exists()) {
//                    directory.mkdirs();
//                }
//                String fileName = KeyGenerator.uuid() + ".mp3";
//                File url = new File(path, fileName);
//                FileUtils.copyInputStreamToFile(file.getInputStream(), url);
//                return ServiceResult.success(fileName);
//            } else {
//                return ServiceResult.success(splitMp3Service.split(file));
//            }
//        } catch (IOException e) {
//            throw new AssertUtils.ValidateException("IO异常");
//        }
        return null;
    }

    @ApiOperation(value = "七牛云上传MP3", produces = MediaType.MULTIPART_FORM_DATA_VALUE)
    @PostMapping(value = "/api/music/file/upload/qiniu")
    public ServiceResult <String> uploadMusicToQiNiu(@RequestParam("file") MultipartFile file) throws IOException, MimeTypeException {
        String uuid = KeyGenerator.uuid();
        FsProperties properties = cacheService.get(CacheConstants.FS_PROPERTIES_CONFIG.name());
        String url = properties.getDomainUrl();
        Map <String, byte[]> map = cacheService.get(CacheConstants.FILE_CACHE.name());
        if (file.getBytes().length < 10 * 1024 * 1024) {
            String fileName = uuid + ".mp3";
            map.put(fileName, file.getBytes());
            return ServiceResult.success(url + fileName);
        } else {
            List <MultipartFile> list = splitMp3Service.split(file, uuid, properties.getLocalPath());
            list.forEach(files -> {
                try {
                    if (files.getBytes().length == file.getBytes().length / 3 * 2) {
                        map.put("split" + 1 + "-" + uuid + ".mp3", files.getBytes());
                    } else if (files.getBytes().length == file.getBytes().length / 3) {
                        map.put("split" + 2 + "-" + uuid + ".mp3", files.getBytes());
                    } else if (files.getBytes().length == file.getBytes().length) {
                        map.put(uuid + ".mp3", list.get(0).getBytes());
                    }
                } catch (IOException io) {
                    throw new RuntimeException(io);
                }

            });
            return ServiceResult.success(url + uuid + ".mp3");
        }
    }
}
